require 'libxml'

class BdController < ApplicationController
  autocomplete :rismid, :h0001
  def analyze
    require 'libxml'
    dn ='marc:http://www.loc.gov/MARC21/slim'
    xml_document = LibXML::XML::Document.file('/home/stephan/workspace/RISMToolKit/app/models/bach-digital.xml')
    if params["extext"]
      rismid=params["extext"]["name"]
    end
    book_xpath = '//marc:record'
    nodes=xml_document.find(book_xpath,dn)
    @countnodes=nodes.size
    @res={}
    nodes.each {|record| record.each {|node|
        node.attributes.each{|att|
          tag=node.attributes[att.name] if att.name=="tag"
          if !@res.key?(tag)
            @res[tag]=[]
          end
          node.children.each{|subf|
            if subf.name=="subfield"
              subf.attributes.each {
                |atts| @res[tag] <<subf.attributes[atts.name] if atts.name=="code" and !@res[tag].include?(subf.attributes[atts.name])
              }
            end
          }
        }
      }
    }
    @endlist=[]
    @res.keys.each{|k| @endlist << k if k}
    @el=@endlist.sort
  end

  def changelog
  end

  def showsubfield
    if params[:subfield]
      @subfield=params[:subfield]
      @tag=@subfield.split('$')[0]
      @code=@subfield.split('$')[1]
      dn ='marc:http://www.loc.gov/MARC21/slim'
      xml_document = LibXML::XML::Document.file('/home/stephan/workspace/RISMToolKit/app/models/bach-digital.xml')
      book_xpath = '//marc:record/marc:datafield[@tag="'+String(@tag)+'"]/marc:subfield[@code="'+String(@code)+'"]'
      @nodes=xml_document.find(book_xpath,dn)
      @countno=@nodes.size if @nodes.size > 0
    end
  end

  def populate
    rismid="B00340000"
    dn ='marc:http://www.loc.gov/MARC21/slim'
    xml_document = LibXML::XML::Document.file('/home/stephan/workspace/RISMToolKit/app/models/bach-digital.xml')
    if params["extext"]
      rismid=params["extext"]["name"]
    end
    book_xpath = '//marc:record/marc:controlfield[@tag="001"][contains(.,"'+rismid+'")]/..'
    nodes=xml_document.find(book_xpath,dn)
    #@old_xml=nodes[0]
    #x=Rismid.find(:first, :conditions=>"h0001='B00340000'").xml
    #@old_xml=LibXML::XML::Document.string(x)

    #@ids=xml_document.find('//marc:record/marc:controlfield[@tag="001"]/text()',dn).to_a.select {|s| !s.to_s.start_with?('4')}
    @ids=xml_document.find('//marc:record',dn)
    @ids.each {|r|
      rismid=String(r.find('marc:controlfield[@tag="001"]/text()',dn)[0])
      bwv=String(r.find('marc:datafield[@tag="240"]/marc:subfield[@code="n"]/text()',dn)[0])
      xml=r.to_s()
      n=Rismid.new(:h0001=>rismid, :bwv=>bwv, :xml=>xml)
      n.save
    }
  end

  def convert
    require 'MarcTools'
        rismid="B00340000"
        if params["extext"]
          rismid=params["extext"]["name"]
        end
        x=Rismid.find(:first, :conditions=>"h0001='"+rismid+"' or bwv='"+rismid+"'")
        if x
          x=x.xml
        @old_xml=LibXML::XML::Document.string(x).root
        @url=String(@old_xml.find('datafield[@tag="856"]/subfield[@code="u"]/text()')[0])
        converter=MarcTools::MarcConverter.new
        @marc_hash=converter.marc_to_hash(@old_xml)
        @marc_hash=converter.changeSubfieldCode(@marc_hash,'650$3', '650$a')
        @marc_hash=converter.moveTag(@marc_hash,'240$n', '240$a')
        @marc_hash=converter.moveTag(@marc_hash,'300$c', '300$a')
        @marc_hash=converter.removeTagbyValue(@marc_hash,'700$a', 'unbekannt')
        @marc_hash=converter.removeTagbyValue(@marc_hash,'657$y', 'unbekannt')
        @new_xml=converter.hash_to_marc(@marc_hash)
      end
      end

  def retrieveFile
    require 'MarcTools'
        #rismid="B00340000"
        x=Rismid.find(:all, :conditions => ["h0001 not LIKE ?", "#{4}%"])
        #x=Rismid.find(:first, :conditions=>"h0001='"+rismid)
        x.each {|tempxml| 
          tempxmlx=tempxml.xml
        @old_xml=LibXML::XML::Document.string(tempxml).root
        @url=String(@old_xml.find('datafield[@tag="856"]/subfield[@code="u"]/text()')[0])
        converter=MarcTools::MarcConverter.new
        @marc_hash=converter.marc_to_hash(@old_xml)
         @marc_hash=converter.changeSubfieldCode(@marc_hash,'650$3', '650$a')
         @marc_hash=converter.moveTag(@marc_hash,'240$n', '240$a')
         @marc_hash=converter.moveTag(@marc_hash,'300$c', '300$a')
        @marc_hash=converter.removeTagbyValue(@marc_hash,'700$a', 'unbekannt')
         @marc_hash=converter.removeTagbyValue(@marc_hash,'657$y', 'unbekannt')
         @new_xml=converter.hash_to_marc(@marc_hash)
        p @new_xml
        }
      end
    

end

